package com.example.mongodb.springbootmongodb.service;

import com.example.mongodb.springbootmongodb.dao.TeacherDao;
import com.example.mongodb.springbootmongodb.po.Teacher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yushizhong
 * @date: 2022-06-30 15:23
 * @version: 1.0
 **/

@Service

public class TeacherService  {



    @Resource
    private TeacherDao teacherDao;

    public  void save(Teacher teacher) {
         teacherDao.save(teacher);
    }

   public List<Teacher> findAll() {
        Sort sort =  Sort.by("age").descending();
        return teacherDao.findAll();
    }


    public void insertBatch() {

        List list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            Teacher teacher = new Teacher();
            teacher.setId(Long.valueOf(i));
            teacher.setAge(10 + i);
            teacher.setName("小明"+i);
            teacher.setSex("女");
            list.add(teacher);
        }
        teacherDao.saveAll(list);
    }

    public List<Teacher> getTeacher(Integer age ) {
        return teacherDao.findTeachersByAgeLessThan(age);
    }

    public void testUpdate(){
        teacherDao.findById(1L).ifPresent(item->{
            item.setName("张三");
            teacherDao.save(item);

        });
    }


    public List<Teacher> testPage() {
        Sort sort = Sort.by("age").ascending();
        PageRequest pageRequest = PageRequest.of(1, 5);
        Page<Teacher> pageResult = teacherDao.findAll(pageRequest);
        System.err.println("【总页数】="+pageResult.getTotalPages());
        System.err.println("【总条数】="+pageResult.getTotalElements());
        System.err.println("【总条数size】="+pageResult.getSize());
        System.err.println("【总条数num】="+pageResult.getNumber());

        return pageResult.getContent();
    }


}
